//
//  addShowOrderViewController.m
//  ZhenPin
//
//  Created by tmosport on 14-8-25.
//  Copyright (c) 2014年 zhenpin. All rights reserved.
//

#import "addShowOrderViewController.h"
#import "MBProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "photoCell.h"

@interface addShowOrderViewController ()
{
    NSArray * imageArray;
    NSMutableArray * dataArray;
    
}
@property (nonatomic, retain) NSArray *logResult;
@property (strong, nonatomic) IBOutlet UIImageView *pImg;
@property (strong, nonatomic) IBOutlet UILabel *bName;
@property (strong, nonatomic) IBOutlet UILabel *productName;
@property (strong, nonatomic) IBOutlet UILabel *placeHolerLabel;
@property (strong, nonatomic) IBOutlet UITextView *evaTF;
@property (strong, nonatomic) NSString *orderid;
@property (strong, nonatomic) NSString *productid;
@property (strong, nonatomic) NSString *productspecid;




@end

@implementation addShowOrderViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setNavigationItem];
    
    imageArray = [[NSArray alloc]initWithObjects:
                  @"profile1.png",
                  @"profile2.png",
                  @"profile3.png",
                  @"profile4.png",
                  @"profile5.png",
                  @"profile6.png",
                  nil];
    //this is the data source of the collection view, it will change based on user behaviors
    dataArray = [[NSMutableArray alloc]initWithObjects:
                 @"plus.png",
                 nil];
    [self dataInit];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]
                                             initWithTitle:@"保存"
                                             style:UIBarButtonItemStyleBordered
                                             target:self
                                             action:@selector(uploadImage:)];
    _evaTF.layer.cornerRadius = 4.0f;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [paragraphStyle setLineSpacing: 3];
    NSString *placeText = @"评价内容长度请控制在5--100字之间，可以将您的使用感受、购物建议、实物照片、拆包过程与大家分享。";
    NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyle};
    
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:placeText attributes:attributes];
    
    _placeHolerLabel.attributedText = attributedString;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]   initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];

}

-(void)setNavigationItem {
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)dismissKeyboard {
    [_evaTF resignFirstResponder];
}

- (void)dataInit{
    
    NSDictionary *params = @{@"memberid": _memberId,
                             @"access_token": _token,
                             @"orderitemid": [NSNumber numberWithInt:_orderitemid]
                             };
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger GET:APIURL@"myzhenpin/getOrderItemDtail.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _logResult = responseObject;
        [self refrshView];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //TODO:错误捕获
    }];
}

-(void)refrshView
{
    
    NSDictionary *contentDic = [_logResult objectAtIndex:0];
    _bName.text = contentDic[@"brandname"];
    _productName.text = contentDic[@"productName"];
    [_pImg sd_setImageWithURL:Return_imageUrl(contentDic[@"imageSource"], 180) placeholderImage:[UIImage imageNamed:@"noimage"] options:SDWebImageRetryFailed];
}

- (void)toSend{
    NSDictionary *varDic = [_logResult objectAtIndex:0];
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.dimBackground = YES;
    HUD.labelText = @"发送评论";
    NSString *evaluatecontent = _evaTF.text;
    if ([evaluatecontent length] == 0||[evaluatecontent isEqual:[NSNull null]]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请正确填写评论" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
    NSDictionary *newparm = @{@"memberid": _memberId,
                              @"access_token": _token,
                              @"orderid": [NSString stringWithFormat:@"%@", varDic[@"orderId"]],
                              @"orderitemid": [NSNumber numberWithInt:_orderitemid],
                              @"productid": [NSString stringWithFormat:@"%@",varDic[@"productId"]],
                              @"productspecid": [NSString stringWithFormat:@"%@",varDic[@"productSpecId"]],
                              @"evaluatecontent": evaluatecontent,
                              };
    
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger POST:APIURL@"myzhenpin/evaluate/addEvaluate.json" parameters:newparm success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *logBack = responseObject;
        if ([logBack[@"isOk"] intValue] == 1) {
            [HUD showAnimated:YES whileExecutingBlock:^{
                sleep(1);
                HUD.mode = MBProgressHUDModeText;
                HUD.labelText = @"发送成功!";
            }completionBlock:^{
                sleep(1);
                [HUD hide:YES afterDelay:1];
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
        }else{
            
            [HUD showAnimated:YES whileExecutingBlock:^{
                HUD.mode = MBProgressHUDModeText;
                HUD.labelText = @"发送失败!";
            }completionBlock:^{
                sleep(1);
                [HUD hide:YES afterDelay:1];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DO:接口回传失败日志
    }];
}

-(void)textViewDidChange:(UITextView *)textView{
    if ([_evaTF.text length] == 0) {
        _placeHolerLabel.hidden = NO;
    }else{
        _placeHolerLabel.hidden = YES;
    }
}
-(NSInteger)numberOfSectionsInCollectionView:
(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView
    numberOfItemsInSection:(NSInteger)section
{
    return dataArray.count >= 3 ? 3 : dataArray.count ;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    photoCell *myCell = [collectionView
                                      dequeueReusableCellWithReuseIdentifier:@"photoCell"
                                      forIndexPath:indexPath];
    NSInteger indexForCollection = indexPath.row;
    
    NSString * imageName = [dataArray objectAtIndex:[indexPath row]];
    
    
    
    myCell.photo.tag = [indexPath row];
    if (dataArray.count <= 3) {
        if (indexForCollection < (dataArray.count - 1)) {
            [myCell.photo setImage:[UIImage imageWithContentsOfFile:imageName]];
        }else{
            [myCell.photo setImage:[UIImage imageNamed:imageName]];
        }
        
        myCell.closeButton.hidden = indexForCollection < (dataArray.count - 1) ? NO : YES;
    }else{
        myCell.closeButton.hidden = NO;
        [myCell.photo setImage:[UIImage imageWithContentsOfFile:imageName]];
    }
    
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapProfileImage:)];
    singleTap.numberOfTapsRequired = 1;
    myCell.photo.userInteractionEnabled = YES;
    [myCell.photo  addGestureRecognizer:singleTap];
    myCell.closeButton.tag = [indexPath row];
    
    
    [myCell.closeButton addTarget:self action:@selector(deletePhoto:)
                 forControlEvents:UIControlEventTouchUpInside];
    return myCell;
}

//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    return UIEdgeInsetsMake(20, 8, 10, 8);
//}


- (void) tapProfileImage:(UITapGestureRecognizer *)gestureRecognizer{
    UIImageView *tableGridImage = (UIImageView*)gestureRecognizer.view;
    NSInteger index = tableGridImage.tag;
    if (index == (dataArray.count -1) )
    {
        //        //添加按钮相应事件
        [self addImage];
    }
    else {
        //点击已经添加的图片
    }
    
}

-(void)addImage{
    UIActionSheet *sheet;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    }
    else {
        
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"从相册选择", nil];
    }
    
    sheet.tag = 255;
    
    [sheet showInView:self.view];
    
}

#pragma mark - actionsheet delegate
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        
        NSUInteger sourceType = 0;
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            switch (buttonIndex) {
                case 0:
                    // 取消
                    return;
                case 1:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                    
                case 2:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
            }
        }
        else {
            if (buttonIndex == 0) {
                
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        
        imagePickerController.delegate = self;
        
        imagePickerController.allowsEditing = YES;
        
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{}];
        
    }
}

- (void)deletePhoto: (UIButton *)sender{
    [dataArray removeObjectAtIndex:sender.tag];
    [self.collectionView reloadData];
}
#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    
    // 将图片写入文件
    
    [imageData writeToFile:fullPath atomically:NO];
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	[picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSString *tempName = [NSString stringWithFormat:@"%u_share.png",arc4random()];
    [self saveImage:image withName:tempName];
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:tempName];
    
//    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    [dataArray insertObject:fullPath atIndex:[dataArray count] - 1];
    [self.collectionView reloadData];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[self dismissViewControllerAnimated:YES completion:^{}];
}

- (IBAction)uploadImage:(UIBarButtonItem *)sender {
//测试数据所有参数均为11
    [self dismissKeyboard];
    NSDictionary *varDic = [_logResult objectAtIndex:0];

    NSString *evaluatecontent = _evaTF.text;
    if ([evaluatecontent length] == 0||[evaluatecontent isEqual:[NSNull null]]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请正确填写评论" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
    if (![self isValidString:evaluatecontent]) {//过滤emoji
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请勿在评价内容中提交表情等符号" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.dimBackground = YES;
    HUD.labelText = @"发送晒单";
    NSDictionary *newparm = @{@"memberid": _memberId,
                              @"access_token": _token,
                              @"orderid": [NSString stringWithFormat:@"%@", varDic[@"orderId"]],
                              @"orderitemid": [NSNumber numberWithInt:_orderitemid],
                              @"productid": [NSString stringWithFormat:@"%@",varDic[@"productId"]],
                              @"productspecid": [NSString stringWithFormat:@"%@",varDic[@"productSpecId"]],
                              @"showtitle": @"showtitle",
                              @"showcontent": evaluatecontent,
                              };

    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager POST:APIURL@"myzhenpinShowOrder/addShowOrder.json" parameters:newparm constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        for (int i =0; i<([dataArray count] - 1); i++) {
            NSString * imageName = [dataArray objectAtIndex:i];
            NSURL *filePath = [NSURL fileURLWithPath:imageName];
            [formData appendPartWithFileURL:filePath name:@"showimages" error:nil];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *logBack = responseObject;
        if ([logBack[@"isOk"] intValue] == 1) {
            [HUD showAnimated:YES whileExecutingBlock:^{
                HUD.mode = MBProgressHUDModeText;
                HUD.labelText = @"发送成功!";
            }completionBlock:^{
                [HUD hide:YES afterDelay:1];
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
        }else{
            [HUD showAnimated:YES whileExecutingBlock:^{
                HUD.mode = MBProgressHUDModeText;
                HUD.labelText = @"发送失败,请稍后重试!";
            }completionBlock:^{
                [HUD hide:YES afterDelay:3];
            }];
        }
        //晒单成功
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //TODO:错误捕获
    }];
}
- (BOOL)isValidString:(NSString *)string
{//过滤emoji表情
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:NSMatchingWithTransparentBounds range:NSMakeRange(0,[string length])];
    
    if (numberOfMatches > 0) {
        return NO;
    }
    
    return YES;
}




- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
